package com.doghome.news.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.doghome.news.dao.UserMapper;
import com.doghome.news.entity.User;
import com.doghome.news.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public Map<String, Object> login(String name, String pwd) {
		User user = userMapper.selectByName(name);
		if (user == null || !user.getUpwd().equals(pwd)) {
			return null;
		}
		user.setUpwd(null);
		String token = UUID.randomUUID().toString();
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			stringRedisTemplate.opsForValue().set(token, objectMapper.writeValueAsString(user), 30, TimeUnit.MINUTES);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("token", token);
		params.put("user", user);
		return params;
	}

	@Override
	public boolean loginOut(String token) {
		return stringRedisTemplate.delete(token);
	}

	@Override
	public boolean repeatName(String name) {
		User user = userMapper.selectByName(name);
		if (user != null) {
			return true;
		}
		return false;
	}

	@Override
	public boolean addUser(User user) {
		int count = -1;
		count = userMapper.insertSelective(user);
		if (count == 1) {
			return true;
		}
		return false;
	}

	@Override
	public PageInfo<User> userByPage(Map<String, Object> params) {
		PageHelper.startPage(params);
		return new PageInfo<User>(userMapper.selectAll(params));
	}

	@Override
	public User userByToken(String token) {
		String userJson = stringRedisTemplate.opsForValue().get(token);
		if (userJson != null) {
			ObjectMapper objectMapper = new ObjectMapper();
			try {
				User user = objectMapper.readValue(userJson, User.class);
				return user;
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
